<template>
  <div class="article-publish-container">
    <div class="nav">
      <Nav />
    </div>
    <el-card class="box-card">
      <el-form ref="articleForm" :model="articleData" label-width="120px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="articleData.title"></el-input>
        </el-form-item>
        <el-form-item id="content" label="文章内容" prop="body.content">
          <el-input type="textarea" v-model="articleData.body.content" id="text" placeholder="请输入内容 (支持MarkDown格式)"></el-input>
        </el-form-item>
        <el-form-item label="文章概述" prop="summary">
          <el-input type="textarea" v-model="articleData.summary"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="publishArticle">发布文章</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { inject, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router.js';
import vuex from '@/vuex.js';
import Nav from '@/views/Layout/nav.vue';
const axios = inject('$axios');
const token = vuex.state.curToken;
console.log(token);

// 文章数据对象，初始化为符合接口要求的结构
const articleData = reactive({
  title: '',
  id: 0,
  body: {
    content: '',
    contentHtml: '<p>这是一段 HTML 格式的文章内容示例</p>'
  },
  category: {
    id: 0,
    avatar: '',
    categoryName: ''
  },
  summary: '',
  tags: []
});

const articleForm = ref(null);
// 创建ref对象，用于获取表单实例

// 发布文章的方法
const publishArticle = async () => {
  if (!articleForm.value.validate()) {
    return;
  }
  try {
    const res = await axios({
      method: 'post',
      url: '/articles/publish',
      headers: {
        Authorization: token
      },
      data: articleData,
    });

    if (res.status === 200) {
      ElMessage.success('文章发布成功');
      router.push('/');
    } else {
      ElMessage.error('文章发布失败，状态码：' + res.status);
    }
  } catch (error) {
    ElMessage.error('文章发布出现错误：' + error.message);
  }
};
</script>

<style scoped>
.article-publish-container {
  padding: 20px;
  display: flex;
  justify-content: center;
  margin-top: 50px;
  width: 100%;
}

.box-card {
  width: 80%;
  max-width: 1200px;
}

/* 文章内容输入框优化 */
::v-deep #text {
  height: 390px !important; /* 固定高度为500px */
  min-height: auto; /* 移除min-height，避免冲突 */
  max-height: 500px; /* 防止用户调整超过500px */
  resize: none; /* 禁用用户调整大小 */
}

/* 其他元素样式调整 */
.el-form-item__label {
  flex: 0 0 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  ::v-deep #text {
    width: 100%;
    height: 400px !important; /* 小屏幕下适当减少高度 */
  }
}
</style>